package cn.com.yang.net;
/**
 * 
 * @author yangyijin
 * @date  2022.07.21 
 */

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

/**
 * X509 apache httpclient
 * @author yangyijin
 *
 */
public class HttpClientUtil {
	public static CloseableHttpClient creatClient() throws IOException, CertificateException {
		try {
			//信任所有证书
			//信任某个证书
			KeyStore trustStore = KeyStore.getInstance("JKS");
			Path path =new File("").toPath();//证书路径
			//
            try (InputStream is = Files.newInputStream(path)) {
	                trustStore.load(is, new char[]{1,2,3,4,5,6});
            }
			SSLContext sslContext =new SSLContextBuilder().loadTrustMaterial(trustStore,new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			// 
			SSLSocketFactory ssf=sslContext.getSocketFactory();
			URL urlClient = new URL("https://eeee.ba.com/dsds");//随意地址
			final String PROXY_ADDR = "172.20.230.5";
		    final int PROXY_PORT = 3128;
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_ADDR, PROXY_PORT));
			HttpsURLConnection httpsConn = (HttpsURLConnection) urlClient.openConnection(proxy);
			httpsConn.setSSLSocketFactory(ssf);
			
			//NoopHostnameVerifier类：作为主机名验证工具，实质上关闭了主机名验证，它接受任何有效的SSL会话
			//并匹配到目标主机
			HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
			SSLConnectionSocketFactory sslConnectionSocketFactory= new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
			return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
}
